/** Mode handler for selecting a map location.
@param map Map object (supporting renderPosition, renderOverlay and getPositionDescription methods).
@param x Center of selection X.
@param y Center of selection Y.
@param r Selection radius, use 0 for anywhere.
@param callback Callback method to invoke when the selection is complete. Callback parameters are (x, y, canceled).
@param context The context of the callback method.
*/
function SelectPositionMode(map, x, y, r, callback, context)
{
	this.map = map;
	this.cursorX = x;
	this.cursorY = y;
	this.startX = x;
	this.startY = y;
	this.radius = r;
	this.callback = callback;
	this.callbackContext = context;
	this.render();
}
SelectPositionMode.prototype =
{
	/** Handle an input action.
	*/
	handleAction: function(action)
	{
		switch(action)
		{
			case "up": this._tryMoveCursor(0, -1); break;
			case "down": this._tryMoveCursor(0, 1); break;
			case "left": this._tryMoveCursor(-1, 0); break;
			case "right": this._tryMoveCursor(1, 0); break;
			case "use":
				this.unrender();
				this.callback.call(this.callbackContext, this.cursorX, this.cursorY, false);
				dhack.removeModeHandler(this);
				break;
			case "cancel":
				this.unrender();
				this.callback.call(this.callbackContext, this.cursorX, this.cursorY, true);
				dhack.removeModeHandler(this);
				break;
			default: return true; break;
		}
		return true;
	},
	/** Try to move the cursor.
	@param xOfs X offset.
	@param yOfs Y offset.
	*/
	_tryMoveCursor: function(xOfs, yOfs)
	{
		var nx = this.cursorX + xOfs;
		var ny = this.cursorY + yOfs;
		if(nx < 0 ||
			ny < 0 ||
			nx >= this.map.width ||
			ny >= this.map.height)
			return;
		
		if(this.radius > 0)
		{
			var sd = Math.abs(this.startX - nx) + Math.abs(this.startY - ny);
			if(sd > this.radius)
				return;
		}
		
		this.unrender();
		this.cursorX = nx;
		this.cursorY = ny;
		this.render();
	},
	/** Rerender the cursor.
	*/
	render: function()
	{
		dhack.logWindow.tempMessage("%f0" +this.map.getPositionDescription(this.cursorX, this.cursorY));
		this.map.renderOverlay(this.cursorX, this.cursorY, null, null, Color.gray);
	},
	/** Unrender the cursor
	*/
	unrender: function()
	{
		this.map.renderPosition(this.cursorX, this.cursorY);
	}
};
